import store from '../store';
import todo from './todo';

const keyboard = {
	37: 'left',
	38: 'rotate',
	39: 'right',
	40: 'down',
	32: 'drop',
	83: 'music',
	82: 'reset',
	80: 'pause',
	72: 'helper',
	69: "exchange"
};

let keydownActive;

const boardKeys = Object.keys(keyboard).map(e => parseInt(e, 10));

const keyDown = (e) => {
	if (e.metaKey === true || boardKeys.indexOf(e.keyCode) === -1) {
		return;
	}
	const type = keyboard[e.keyCode];
	if (type === "exchange") {
		return store.commit("buttons");
	}
	if (type === "helper") {
		return store.commit("help", !store.state.help);
	}

	if (type === keydownActive) {
		return;
	}
	keydownActive = type;
	console.log(type)
	todo[type].down(store);
};

const keyUp = (e) => {
	if (e.metaKey === true || boardKeys.indexOf(e.keyCode) === -1) {
		return;
	}
	const type = keyboard[e.keyCode];
	if (type === "exchange") {
		return;
	}
	if (type === "helper") {
		return;
	}
	if (type === keydownActive) {
		keydownActive = '';
	}
	todo[type].up(store);
};

document.addEventListener('keydown', keyDown, true);
document.addEventListener('keyup', keyUp, true);
